package com.friend.chat.websocket

import android.os.Handler
import android.util.Log
import com.friend.chat.base.NetUrlConstant.WEBSOCKET_URL
import com.friend.chat.chat.CHAT_SYSTEM
import com.friend.chat.page.bean.UserBean
import com.friend.chat.utils.SPUtils
import com.google.gson.Gson
import org.greenrobot.eventbus.EventBus
import org.java_websocket.client.WebSocketClient
import org.java_websocket.drafts.Draft_6455
import org.java_websocket.handshake.ServerHandshake
import java.net.URI
import java.util.*

/**
 * @des 双重检查锁webSocket
 * @author batie fancy
 * @date 2022/8/5
 */
class WebSocketManager() {
    private var mWebSocketClient: WebSocketClient? = null
    private val BASE_URL = ""
    private val TAG = "WebSocketManager"
    private var mTimer: Timer? = null

    companion object {
        val instance by lazy(LazyThreadSafetyMode.SYNCHRONIZED) { WebSocketManager() }
    }

    fun initClient(): WebSocketManager {
        //wss://www.godboy.cn/webSocket
        //wss://www.godboy.cn/webSocket
        Log.e("---->", "WebSocketClient初始化")
        var userBean: UserBean = SPUtils.getInstance().getObject("user") as UserBean
        mWebSocketClient =
            object :
                WebSocketClient(URI.create(WEBSOCKET_URL), Draft_6455()) {
                override fun onOpen(handshakedata: ServerHandshake?) {
                    Log.e("---->", "WebSocketClient成功")
                    //让后端记住自己的uid
                    initTimer(userBean.uid)

                }

                override fun onMessage(message: String?) {
                    Log.e("---->", "receive==>$message")
                    message?.apply {
                        var messageBean: ChatMessageBean =
                            Gson().fromJson(message, ChatMessageBean::class.java)
                        EventBus.getDefault().post(messageBean)
                    }
                }

                override fun onClose(code: Int, reason: String?, remote: Boolean) {
                    Log.e("关闭原因---->", reason + "")

                }

                override fun onError(ex: Exception?) {
                    Log.e("错误原因---->", ex?.message + "")

                }
            }
        mWebSocketClient?.addHeader("o", "llll")
        mWebSocketClient?.connect()

        return this
    }

    fun open() {
        if (mWebSocketClient == null) {
            initClient()
        } else {
            if (mWebSocketClient!!.isClosed) {
                mWebSocketClient!!.connect()
            } else {
                mWebSocketClient!!.reconnect()
            }
        }
    }

    private fun close() {
        if (mWebSocketClient != null) {
            mWebSocketClient!!.close()
            mWebSocketClient = null
        }

    }

    fun sendMessage(text: String) {
        if (mWebSocketClient == null || mWebSocketClient!!.isClosed||mWebSocketClient!!.isClosing) {
            Log.e(TAG, "mWebSocket 为null或已经关闭")
            open()
            return
        }
        mWebSocketClient?.send(text)
        Log.e("---->", "send==>$text")
    }

    /**
     * 定时执行器
     * 秒后执行，每隔20秒执行一次
     * 让服务器知道还活着，断线重连
     */
    private fun initTimer(uid:String) {
        mTimer = Timer()
        mTimer!!.schedule(object : TimerTask() {
            override fun run() {
                if (mWebSocketClient != null){
                    if (!mWebSocketClient!!.isClosed){
                        //保持通道连接
                        sendMessage(Gson().toJson(ChatMessageBean(uid, "0", CHAT_SYSTEM,-1, "hahaha")))
                    }else{
                       mWebSocketClient!!.reconnect()
                    }
                }else{
                   Handler().postDelayed({ initClient() },200)
                }


            }
        }, 500, 20000)
    }
}